<?php
class PassportService
{
    static private $__login_cookie_name = 'logged_user';
    static private $__login_cookie_key  = 'Joboto_xsw2XSW@';
    static private $__secure_key        = 'Joboto_xsw2XSW@';
    
    const JOBOTO_ADMIN = 'JobotoAdmin'; // 登录周伯通后台系统
    const WEI_ADMIN    = 'WeiAdmin';    // 登录微账号后台系统

    static public function isLoggedIn()
    {
        return (boolean)self::getLoggedUid();
    }
    
    static public function getLoggedUid()
    {
        return $_SESSION['mid'] ? $_SESSION['mid'] : self::getCookieUid();
    }
    
    static public function getCookieUid()
    {
        import('ORG.Crypt.Crypt');
        $crypt  = new Crypt();
        $cookie = explode(';', $crypt->decrypt(cookie(self::$__login_cookie_name), self::$__secure_key));
        if ($cookie[0] === self::$__login_cookie_key) {
            $uid = $cookie[1];
            return $uid;
        }else {
            return NULL;
        }
    }
    
    static public function login($uid, $expire = 3600)
    {
        $uid = intval($uid);
        $_SESSION['mid'] = $uid;
        
        import('ORG.Crypt.Crypt');
        $crypt  = new Crypt();
        $cookie = $crypt->encrypt(self::$__login_cookie_key . ";{$uid}", self::$__secure_key);
        cookie(self::$__login_cookie_name, $cookie, $expire);
        
        return TRUE;
    }
    
    static public function logout()
    {
        $_SESSION['mid'] = NULL;
        cookie(self::$__login_cookie_name, NULL);
        
        self::logoutAdmin();
    }
    
    static public function isLoggedInAdmin($admin_type = self::JOBOTO_ADMIN)
    {
        return (boolean)self::getLoggedAdminUid($admin_type);
    }
    
    static  public function getLoggedAdminUid($admin_type = self::JOBOTO_ADMIN)
    {
        return $_SESSION[$admin_type];
    }
    
    static public function loginAdmin($uid, $admin_type = self::JOBOTO_ADMIN)
    {
        $_SESSION[$admin_type] = $uid;
    }
    
    static public function logoutAdmin($admin_type = self::JOBOTO_ADMIN)
    {
        unset($_SESSION[$admin_type]);
    }
}